package scigest.metadata;

import java.io.IOException;
import java.util.List;

import org.apache.commons.chain.Context;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import scigest.configuration.ConfigKeys;
import scigest.configuration.ScigestConfiguration;

/**
 * This is a metadata provider abstract class.
 * The base class provided Solr ingestion function that all handlers will need.
 * 
 * @author Feiyi Wang
 *
 */
public abstract class MetadataHandler {

	@Autowired
	@Qualifier("solrServer")
	private SolrServer server;

	@Autowired
	@Qualifier("scigestConf")
	private ScigestConfiguration sc;

	
	public abstract List<String> getFieldList();
	
	/**
	 * Construct a unique doc id, composed by projectName + ".meta"
	 * We need some conventions here to establish the uniqueness of 
	 * this ID. 
	 * 
	 * @return a String representation of doc ID
	 */
	private String getDocId() {
		return  sc.getString(ConfigKeys.PROJECT_NAME) + ".meta" ;
	}
	
	
	private String getTitle() {
		String title = sc.getString(ConfigKeys.PROJECT_TITLE);
		if (title.isEmpty())
			title = sc.getString(ConfigKeys.PROJECT_NAME);
		return title;
	}
	
	public boolean ingestSolr(Context ctx) throws SolrServerException, IOException {
		assert server != null;

		SolrInputDocument doc = new SolrInputDocument();
		
		doc.addField("id",  getDocId());
		doc.addField("title", getTitle());
		doc.addField("type", ConfigKeys.META_TYPE);
		
		List<String> fieldList = getFieldList();
		
		for (String field : fieldList) {			
			doc.addField(field, (String) ctx.get(field));
		}
		
		server.add(doc);
		server.commit();
		
		return true;
	}
}
